package com.christina.engine.service.executor;

import com.christina.engine.execution.model.ExecutionRequest;
import com.christina.engine.execution.model.ExecutionResult;
import lombok.extern.slf4j.Slf4j;

/**
 * 抽象服务执行器
 * 提供服务执行器的通用实现
 * 
 * @author Christina
 */
@Slf4j
public abstract class AbstractServiceExecutor implements ServiceExecutor {
    
    protected final String serviceType;
    protected final String name;
    protected volatile boolean available = true;
    
    protected AbstractServiceExecutor(String serviceType, String name) {
        this.serviceType = serviceType;
        this.name = name;
    }
    
    @Override
    public ExecutionResult execute(ExecutionRequest request) {
        if (!isAvailable()) {
            return ExecutionResult.builder()
                    .success(false)
                    .errorMessage("Service executor is not available: " + name)
                    .build();
        }
        
        if (!supports(request.getServiceType())) {
            return ExecutionResult.builder()
                    .success(false)
                    .errorMessage("Unsupported service type: " + request.getServiceType())
                    .build();
        }
        
        try {
            log.debug("Executing request for service type: {}", request.getServiceType());
            return doExecute(request);
        } catch (Exception e) {
            log.error("Failed to execute request for service type: {}", request.getServiceType(), e);
            return ExecutionResult.builder()
                    .success(false)
                    .errorMessage("Execution failed: " + e.getMessage())
                    .build();
        }
    }
    
    @Override
    public String getSupportedServiceType() {
        return serviceType;
    }
    
    @Override
    public boolean supports(String serviceType) {
        return this.serviceType.equalsIgnoreCase(serviceType);
    }
    
    @Override
    public String getName() {
        return name;
    }
    
    @Override
    public boolean isAvailable() {
        return available;
    }
    
    /**
     * 设置执行器可用性
     * 
     * @param available 是否可用
     */
    protected void setAvailable(boolean available) {
        this.available = available;
    }
    
    /**
     * 执行具体的服务逻辑
     * 子类必须实现此方法
     * 
     * @param request 执行请求
     * @return 执行结果
     */
    protected abstract ExecutionResult doExecute(ExecutionRequest request);
}